#include "RingQueue.hpp"
#include "Task.hpp"
#include <pthread.h>
#include <cstdio>
#include <ctime>
#include <cstdlib>
#include <sys/types.h>
#include <unistd.h>

std::string SelfName()
{
    char name[128];
    snprintf(name, sizeof(name), "thread[0x%x]", pthread_self());
    return name;
}

void* ProducterRoutine(void* rq)
{
    //RingQueue<int>* ringqueue = static_cast<RingQueue<int>*>(rq);
    RingQueue<Task>* ringqueue = static_cast<RingQueue<Task>*>(rq);
    while(true)
    {
        //version1
        // int data = rand() % 10 + 1;
        // ringqueue->push(data);
        // std::cout << "生产完成, 生产的数据是: " << data << std::endl;
        //sleep(1);

        //version2
        //构建or获取一个任务 --- 这个是要花时间的!
        int x = rand() % 10;
        int y = rand() % 5;
        char op = oper[rand()%oper.size()];
        Task t(x, y, op, mymath);
        //生产任务
        ringqueue->push(t);
        //输出提示
        std::cout << SelfName() << ", 生产者派发了一个任务: " << t.toTaskString() << std::endl;

        //sleep(1);
    }
}
void* ConsumerRoutine(void* rq)
{
    //RingQueue<int>* ringqueue = static_cast<RingQueue<int>*>(rq);
    RingQueue<Task>* ringqueue = static_cast<RingQueue<Task>*>(rq);
    while(true)
    {
        //version 1
        // int data;
        // ringqueue->pop(&data);
        // std::cout << "消费完成, 消费的数据是: " << data << std::endl;
        // //sleep(1);

        //version2
        Task t;
        //消费任务
        ringqueue->pop(&t);
        std::string result = t();//消费也是要花时间的!
        std::cout << SelfName() << ", 消费者消费了一个任务: " << result << std::endl;
        //sleep(1);
    }
}

int main()
{
    srand((unsigned int)time(nullptr) ^ getpid() ^ pthread_self() ^ 0x1232324);
    RingQueue<Task>* rq = new RingQueue<Task>();

    //单生产, 单消费, 多生产, 多消费 --> 只要保证,最终进行临界区的是一个生产,一个消费就行!
    //多生产,多消费的意义??
    pthread_t c[8], p[4];
    for(int i = 0; i < 4; ++i) pthread_create(p + i, nullptr, ProducterRoutine, rq);
    for(int i = 0; i < 8; ++i) pthread_create(c + i, nullptr, ConsumerRoutine, rq);

    for(int i = 0; i < 4; ++i) pthread_join(p[i], nullptr);
    for(int i = 0; i < 8; ++i) pthread_join(c[i], nullptr);

    delete rq;
    return 0;
}